<template>
	<view class="page notifications-page">
		<!-- 自定义导航栏 -->
		<br>
		<ob-navbar title="系统通知" :show-back="true" />
		<br>
		
		<view class="content">
			<!-- 通知分类选项卡 -->
			<view class="tabs-section">
				<view class="tabs-container">
					<view 
						v-for="(tab, index) in tabs" 
						:key="index"
						class="tab-item" 
						:class="{ active: currentTab === tab.value }"
						@click="switchTab(tab.value)"
					>
						<text class="tab-text">{{ tab.label }}</text>
						<view v-if="tab.count > 0" class="tab-badge">{{ tab.count }}</view>
					</view>
				</view>
			</view>
			
			<!-- 操作栏 -->
			<view class="actions-section">
				<button 
					class="action-btn mark-read" 
					:disabled="selectedNotifications.length === 0"
					@click="markAsRead"
				>
					标记已读
				</button>
				<button 
					class="action-btn delete" 
					:disabled="selectedNotifications.length === 0"
					@click="deleteNotifications"
				>
					删除
				</button>
				<button class="action-btn clear-all" @click="clearAllNotifications">清空全部</button>
			</view>
			
			<!-- 通知列表 -->
			<view class="notifications-section">
				<view class="notifications-list">
					<view 
						v-for="notification in filteredNotifications" 
						:key="notification.id"
						class="notification-item"
						:class="{ 'unread': !notification.isRead }"
						@click="handleNotificationClick(notification)"
					>
						<view class="select-checkbox" @click.stop="toggleSelect(notification)">
							<text class="checkbox-icon">{{ notification.selected ? '✓' : '' }}</text>
						</view>
						
						<view class="notification-icon" :class="getNotificationIconClass(notification.type)">
							<text class="icon-text">{{ getNotificationIcon(notification.type) }}</text>
						</view>
						
						<view class="notification-content">
							<view class="notification-header">
								<text class="notification-title">{{ notification.title }}</text>
								<text class="notification-time">{{ formatTime(notification.createTime) }}</text>
							</view>
							<text class="notification-desc">{{ notification.content }}</text>
							<view v-if="notification.actionUrl" class="notification-action">
								<text class="action-text">点击查看详情</text>
							</view>
						</view>
						
						<view v-if="!notification.isRead" class="unread-dot"></view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="filteredNotifications.length === 0" class="empty-state">
					<ob-empty 
						:image="'/static/images/empty-notifications.png'"
						title="暂无通知"
						:description="getEmptyDescription()"
					/>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import messageApi from '../../api/message.js'
import { formatDistanceToNow } from '../../utils/common.js'

// 响应式数据
const notifications = ref([])
const currentTab = ref('all')
const isLoading = ref(false)

// 通知分类选项卡
const tabs = ref([
	{ label: '全部', value: 'all', count: 0 },
	{ label: '系统', value: 'system', count: 0 },
	// { label: '好友', value: 'friend', count: 0 },
	// { label: '群聊', value: 'group', count: 0 },
	// { label: '订单', value: 'order', count: 0 }
])

// 计算属性
const filteredNotifications = computed(() => {
	if (currentTab.value === 'all') {
		return notifications.value
	}
	
	return notifications.value.filter(notification => 
		notification.type === currentTab.value
	)
})

const selectedNotifications = computed(() => {
	return notifications.value.filter(notification => notification.selected)
})

// 生命周期
onMounted(() => {
	loadNotifications()
})

// 方法
const loadNotifications = async () => {
	try {
		isLoading.value = true
		const response = await messageApi.getNotifications()
		notifications.value = (response.list || []).map(notification => ({
			...notification,
			selected: false
		}))
		
		// 更新各分类计数
		updateTabCounts()
		
	} catch (error) {
		console.error('加载通知列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const updateTabCounts = () => {
	const counts = {
		all: notifications.value.filter(n => !n.isRead).length,
		system: notifications.value.filter(n => n.type === 'system' && !n.isRead).length,
		friend: notifications.value.filter(n => n.type === 'friend' && !n.isRead).length,
		group: notifications.value.filter(n => n.type === 'group' && !n.isRead).length,
		order: notifications.value.filter(n => n.type === 'order' && !n.isRead).length
	}
	
	tabs.value.forEach(tab => {
		tab.count = counts[tab.value] || 0
	})
}

const switchTab = (tabValue) => {
	currentTab.value = tabValue
	// 清除所有选择
	notifications.value.forEach(notification => {
		notification.selected = false
	})
}

const formatTime = (timestamp) => {
	if (!timestamp) return ''
	return formatDistanceToNow(timestamp)
}

const getNotificationIcon = (type) => {
	const iconMap = {
		system: 'S',
		friend: 'F',
		group: 'G',
		order: 'O',
		default: 'N'
	}
	return iconMap[type] || iconMap.default
}

const getNotificationIconClass = (type) => {
	return `type-${type}`
}

const getEmptyDescription = () => {
	const descMap = {
		all: '暂无通知消息',
		system: '暂无系统通知',
		friend: '暂无好友通知',
		group: '暂无群聊通知',
		order: '暂无订单通知'
	}
	return descMap[currentTab.value] || '暂无通知'
}

const toggleSelect = (notification) => {
	notification.selected = !notification.selected
}

const handleNotificationClick = async (notification) => {
	// 标记为已读
	if (!notification.isRead) {
		try {
			await messageApi.markNotificationAsRead(notification.id)
			notification.isRead = true
			updateTabCounts()
		} catch (error) {
			console.error('标记通知已读失败:', error)
		}
	}
	
	// 处理点击跳转
	if (notification.actionUrl) {
		uni.navigateTo({
			url: notification.actionUrl
		})
	}
}

const markAsRead = async () => {
	if (selectedNotifications.value.length === 0) return
	
	try {
		const ids = selectedNotifications.value.map(n => n.id)
		await messageApi.batchMarkNotificationsAsRead(ids)
		
		// 更新本地状态
		selectedNotifications.value.forEach(notification => {
			notification.isRead = true
			notification.selected = false
		})
		
		updateTabCounts()
		
		uni.showToast({
			title: '已标记为已读',
			icon: 'success'
		})
	} catch (error) {
		console.error('标记已读失败:', error)
		uni.showToast({
			title: '操作失败',
			icon: 'none'
		})
	}
}

const deleteNotifications = () => {
	if (selectedNotifications.value.length === 0) return
	
	uni.showModal({
		title: '删除通知',
		content: `确定要删除选中的${selectedNotifications.value.length}条通知吗？`,
		confirmText: '删除',
		cancelText: '取消',
		confirmColor: '#ff4757',
		success: async (res) => {
			if (res.confirm) {
				try {
					const ids = selectedNotifications.value.map(n => n.id)
					await messageApi.batchDeleteNotifications(ids)
					
					// 从列表中移除
					notifications.value = notifications.value.filter(n => !n.selected)
					
					updateTabCounts()
					
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('删除通知失败:', error)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

const clearAllNotifications = () => {
	uni.showModal({
		title: '清空通知',
		content: '确定要清空所有通知吗？此操作不可恢复。',
		confirmText: '清空',
		cancelText: '取消',
		confirmColor: '#ff4757',
		success: async (res) => {
			if (res.confirm) {
				try {
					await messageApi.clearAllNotifications()
					notifications.value = []
					updateTabCounts()
					
					uni.showToast({
						title: '清空成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('清空通知失败:', error)
					uni.showToast({
						title: '清空失败',
						icon: 'none'
					})
				}
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.notifications-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.content {
	padding: 0;
}

.tabs-section {
	background: #FFFFFF;
	margin: 15px;
	border-radius: 8px;
	overflow: hidden;
}

.tabs-container {
	display: flex;
	padding: 0 10px;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 15px 0;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 4px;
	
	&.active {
		.tab-text {
			color: #495057;
			font-weight: 600;
		}
		
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 30px;
			height: 2px;
			background: #495057;
		}
	}
}

.tab-text {
	font-size: 14px;
	color: #999999;
}

.tab-badge {
	background: #DC3545;
	color: #FFFFFF;
	font-size: 10px;
	padding: 2px 5px;
	border-radius: 8px;
	min-width: 16px;
	text-align: center;
}

.actions-section {
	background: #FFFFFF;
	margin: 0 15px 15px;
	border-radius: 8px;
	padding: 15px 20px;
	display: flex;
	gap: 10px;
}

.action-btn {
	flex: 1;
	height: 36px;
	border: none;
	border-radius: 6px;
	font-size: 12px;
	
	&.mark-read {
		background: #F8F9FA;
		color: #495057;
		border: 1px solid #E9ECEF;
	}
	
	&.delete {
		background: #DC3545;
		color: #FFFFFF;
	}
	
	&.clear-all {
		background: #F8F9FA;
		color: #6C757D;
		border: 1px solid #E9ECEF;
	}
	
	&:disabled {
		background: #F8F9FA !important;
		color: #CED4DA !important;
		border-color: #F0F0F0 !important;
	}
}

.notifications-section {
	background: #FFFFFF;
	margin: 0 15px;
	border-radius: 8px;
	overflow: hidden;
}

.notifications-list {
	padding: 0 20px;
}

.notification-item {
	display: flex;
	align-items: flex-start;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	position: relative;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.unread {
		background: linear-gradient(90deg, #F8F9FA 0%, transparent 100%);
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.select-checkbox {
	width: 18px;
	height: 18px;
	border: 1px solid #CED4DA;
	border-radius: 3px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 12px;
	margin-top: 2px;
	background: #FFFFFF;
}

.checkbox-icon {
	font-size: 10px;
	color: #495057;
}

.notification-icon {
	width: 36px;
	height: 36px;
	border-radius: 18px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 12px;
	margin-top: 2px;
	
	.icon-text {
		font-size: 14px;
		font-weight: 600;
	}
	
	&.type-system {
		background: #F8F9FA;
		border: 1px solid #E9ECEF;
		color: #6C757D;
	}
	
	&.type-friend {
		background: #E3F2FD;
		border: 1px solid #BBDEFB;
		color: #1976D2;
	}
	
	&.type-group {
		background: #E8F5E8;
		border: 1px solid #C8E6C9;
		color: #388E3C;
	}
	
	&.type-order {
		background: #FFF3E0;
		border: 1px solid #FFCC02;
		color: #F57C00;
	}
}

.notification-content {
	flex: 1;
	min-width: 0;
}

.notification-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 6px;
}

.notification-title {
	font-size: 15px;
	font-weight: 500;
	color: #333333;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.notification-time {
	font-size: 12px;
	color: #999999;
	flex-shrink: 0;
}

.notification-desc {
	font-size: 13px;
	color: #666666;
	line-height: 1.4;
	margin-bottom: 8px;
}

.notification-action {
	margin-top: 6px;
}

.action-text {
	font-size: 12px;
	color: #495057;
	text-decoration: underline;
}

.unread-dot {
	position: absolute;
	top: 18px;
	right: 0;
	width: 8px;
	height: 8px;
	background: #DC3545;
	border-radius: 50%;
}

.empty-state {
	padding: 50px 20px;
	text-align: center;
}
</style>